#include <REGX52.H>
#include <intrins.h>
sbit DS1302_CE=P3^5;
sbit DS1302_IO=P3^4;
sbit DS1302_SCLK=P3^6;
#define  s   0x80
#define  mi    0x82
#define  h     0x84
#define  d     0x86
#define  mo    0x88
#define  a     0x8a
#define  y     0x8c

unsigned int i;
void Init_Ds1302(){
	DS1302_CE=0;
	DS1302_SCLK=0;
}
void DS1302_wirtebyte(unsigned char Command,Data){
	DS1302_CE=1;
	for(i=0;i<8;i++){
		DS1302_IO=Command&(0x01<<i);
		DS1302_SCLK=1;
		DS1302_SCLK=0;
	}
	for(i=0;i<8;i++){
		DS1302_IO=Data&(0x01<<i);
		DS1302_SCLK=1;
		DS1302_SCLK=0;
	}
	DS1302_CE=0;
}
unsigned char Ds1302_Readbyte(unsigned char Command){
	unsigned char Data=0;
	DS1302_CE=1;
	Command|=0x01;
	for(i=0;i<8;i++){
		DS1302_IO=Command&(0x01<<i);
		DS1302_SCLK=0;
		DS1302_SCLK=1;
	}
	for(i=0;i<8;i++){
		DS1302_SCLK=1;
		DS1302_SCLK=0;
		if(DS1302_IO){
			Data|=(0x01<<i);
		}
	}
	DS1302_CE=0;
	DS1302_IO=0;//不置零，会导致乱读数
	return Data;
}
void Set_Time(unsigned char *p){
	DS1302_wirtebyte(0x8e,0x00);//关闭写入保护
	DS1302_wirtebyte(s,(p[5]/10)*16+p[5]%10);
	DS1302_wirtebyte(mi,((p[4]/10)<<4)+p[4]%10);
	DS1302_wirtebyte(h,((p[3]/10)<<4)+p[3]%10);
	DS1302_wirtebyte(d,((p[2]/10)<<4)+p[2]%10);
	DS1302_wirtebyte(mo,((p[1]/10)<<4)+p[1]%10);
	DS1302_wirtebyte(a,((p[6]/10)<<4)+p[6]%10);
	DS1302_wirtebyte(y,((p[0]/10)<<4)+p[0]%10);
	DS1302_wirtebyte(0x8e,0x80);//开启写入保护
}
void Read_Time(unsigned char *p){
	unsigned char temp;
	temp=Ds1302_Readbyte(y);
	p[0]=(temp>>4)*10+temp%16;
	temp=Ds1302_Readbyte(mo);
	p[1]=(temp>>4)*10+temp%16;
	temp=Ds1302_Readbyte(d);
	p[2]=(temp>>4)*10+temp%16;
	temp=Ds1302_Readbyte(h);
	p[3]=(temp>>4)*10+temp%16;
	temp=Ds1302_Readbyte(mi);
	p[4]=(temp>>4)*10+temp%16;
	temp=Ds1302_Readbyte(s);
	p[5]=(temp>>4)*10+temp%16;
	temp=Ds1302_Readbyte(a);
	p[6]=(temp>>4)*10+temp%16;
}